<template>
  <div ref="mgrDialog" class="dialog-wrap">
     <el-dialog title="绑定农产品列表" :visible.sync="DialogVisible" border @close="handleCancel">
        <el-button type="primary" @click="bindProduct">绑定农产品</el-button>
         <el-table :data="bindProductList">
          <el-table-column property="cropName" label="农产品名称" width="150"></el-table-column>
          <el-table-column property="landArea" label="种植面积" width="200"></el-table-column>
          <el-table-column property="plantDate" label="种植日期"></el-table-column>
          <el-table-column
            label="操作"
            width="100">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--BIND PRODUCT-->
         <el-dialog 
           :title="headerTitle" 
           width="40%"  
           :visible.sync="innerVisible" 
           append-to-body>
          <el-row :gutter="20">
            <el-form
              
              ref="dialogForm"
              :rules="rules"
              size="mini"
              :label-width="formLabelWidth"
              :model.sync="editForm"
            >
              <el-col :span="22">
                <el-form-item label="作物名称" prop="cropName">
                <el-select 
                    v-model="editForm.cropName"
                    multiple
                    :loading="cropNameLoading"
                    >
                    <el-option
                      v-for="item in croplist"
                      :key="item.cropName"
                      :label="item.cropName"
                      :value="item.cropName">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item label="作物编号" prop="cropNo">
                <el-select v-model="cropNos" disabled multiple placeholder="请选择">
                    <el-option
                      v-for="item in croplist"
                      :key="item.cropNo"
                      :label="item.cropNo"
                      :value="item.cropNo">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item label="土地编号" prop="landNo">
                  <el-select v-model="editForm.landNo" placeholder="土地编号" @change="handleArea">
                    <el-option v-for="(item,key) in blockList" :label="item.code" :value="item.code"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item label="土地面积" prop="landArea">
                  <el-input v-model="editForm.landArea" autocomplete="off" placeholder="请输入土地面积"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item label="种植日期" prop="plantDate">
                  <el-date-picker value-format="yyyy-MM-dd" v-model="editForm.plantDate" type="date" placeholder="选择种植日期"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="22">
                <el-form-item label="预计收获日期" prop="expectedHarvestDate">
                  <el-date-picker value-format="yyyy-MM-dd" v-model="editForm.expectedHarvestDate" type="date" placeholder="选择预计收获日期"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-form>
          </el-row>

          <div slot="footer" class="dialog-footer">
            <el-button size="mini" type="primary" @click="confirm">确定</el-button>
            <el-button size="mini" type="danger" @click="innerVisible = false">取消</el-button>
          </div>
    </el-dialog>
    <!--BIND PRODUCT-->
         <div slot="footer" class="dialog-footer">
          <el-button @click="handleCancel">取 消</el-button>
          <!-- <el-button type="primary" @click="innerVisible = true">打开内层 Dialog</el-button> -->
        </div>
      </el-dialog>
   
  </div>
</template>


<script>
import { getRolesTree, getRoleTreeList } from "@/api/admin/roles";
import { getUserInfo } from "@/api/user";
import { convertDataToTree } from "@/utils/util";
import InputTree from "@/components/InputTree";
import { searchCropInBind } from '@/api/farm/production'
import { listBlock, farmBindProduct, getBindProduct, deleteBindProduct} from  "@/api/farm/gis"

export default {
  props:['farmId','form','visible','type'],
  components: {
    InputTree
  },
  computed:{
    cropNos(){
      let cropNos=[];
      //this.croplist.find((value,index,arr)=>value.code == item)
      if(this.editForm.cropName && Array.isArray(this.editForm.cropName) &&this.editForm.cropName.length > 0){
        this.editForm.cropName.map((item)=>{ 
          cropNos.push(this.croplist[this.croplist.findIndex((value,index,arr)=>{
              console.log(value.cropName);
              return value.cropName == item
          })].cropNo)
        })
      }
     
      return cropNos;
    }
  },
  watch: {
    form(newVal, oldVal) {
      if (newVal != null) {
        this.editForm = newVal;
      } else {
        this.editForm = this.defaultForm;
      }
    },
    farmId(val){
          if(val){
            // 获取当前地块
           listBlock(this.farmId).then((res)=>{
               //console.log(res);
               this.blockList = res.data.data;
               console.log(this.blockList);
               console.log(111)
            })
            //获取已绑定的农产品列表
            getBindProduct(this.farmId, 1, 10)
            .then((res) => {
               this.bindProductList = res.data.data.records;
            })
          }
    }, 
    visible(val) {
      this.DialogVisible = val;
      if (this.form === null) {
        this.editForm = this.defaultForm;
      }
    }
  },
  created(){
    // 获取所有的农产品
	  searchCropInBind()
	  .then((res)=>{
         this.croplist = res.data.data;
    });
  }, 
  data() {
    return {
      editType:1,// 新增/编辑
      innerVisible:false,
      bindProductList:[],
      cropNameLoading:false,
      blockList:[], // 当前农场所有土地地块
      selectNo:'',
      selectArea:'',
      timeout:  null,
      croplist:[],
      headerTitle: "绑定农产品",
      DialogVisible: false,
      defaultForm: {
        name: "",
        chargePerson: "",
        phone: "",
        crop: "",
        lot: "",
        address: "",
        pic: ""
      },
      roleTree: [],
      testEquipmentGroup: [
        {
          checked: true,
          iconSkin: null,
          id: 0,
          name: "根目录",
          open: true,
          pId: 0
        },
        {
          checked: null,
          iconSkin: null,
          id: 1,
          name: "继电器设备",
          open: true,
          pId: 0
        },
        {
          checked: null,
          iconSkin: null,
          id: 2,
          name: "采集设备",
          open: true,
          pId: 0
        }
      ],
      roleTreeProps: {
        children: "childrenNodes",
        label: "name",
        value: "id"
      },
      editForm: {
		    cropName:[],
        cropNo:[],
        landNo:'',
        landArea:'',
        plantDate:'',
        expectedHarvestDate:''
	    },
      formLabelWidth: "100px",
      //验证规则
      rules: {
        cropName: [
          { required: true, message: "请输入作物名称", trigger: "blur" }
        ],
        //cropNo: [{ required: true, message: "请输入作物编号"}]
      }
    };
  },
  mounted() {
    this.getRoleTree();
  },
  methods: {
    // 新增绑定
    bindProduct(){
      if (this.editType == 1 && this.editForm.id) {
            delete this.editForm.id
      }
      this.innerVisible = true;
      this.editType = 1;
      this.editForm.plantDate = '';
       this.editForm.expectedHarvestDate = '';
       this.editForm.cropName = [];
       this.editForm.landNo='';
       this.editForm.landArea = ''
    },
    // 编辑记录
    handleEdit(row){
       //console.log(row);
       this.editType = 2;
       this.innerVisible = true;
       this.editForm.id = row.id;
       this.editForm.cropName = row.cropName.split(',');
       this.editForm.landArea = row.landArea;
       this.editForm.landNo = row.landNo;
       this.editForm.plantDate = row.plantDate;
       this.editForm.expectedHarvestDate = row.expectedHarvestDate
    },
    // 删除记录
    handleDelete(row){
      deleteBindProduct(row.id).then((res)=>{
        	this.$message({
            	type: 'success',
              message: '删除成功!',
              duration: 500,
              onClose:()=>{
                getBindProduct(this.farmId, 1, 10)
                .then((res) => {
                  this.bindProductList = res.data.data.records;
                })
              }
          });
      })
    },
    // 关闭外层dialog
    handleCancel(){
      this.DialogVisible = false;
      this.$emit('cancel');
    },
   
    //选中土地编号填充土地面积
    handleArea(item){
      let selectFarm = this.blockList.find((value,index,arr)=>value.code == item);
      console.log(this.selectFarm.area);
      this.editForm.landArea = selectFarm.area;
    },
    // 获取树形菜单
    getRoleTree() {
      getRoleTreeList().then(res => {
        console.log("-----------获取树形菜单-----------");
        console.log(res);
        //this.roleTree = convertDataToTree(res.data);
        this.roleTree = convertDataToTree(this.testEquipmentGroup);
      });
    },
    resetDialog() {
      this.DialogVisible = false;
      this.editForm = null;
      this.$emit("cancel");
    },
    //上级角色选择
    roleSelect(data) {
      this.editForm.pid = data.id;
    },
    // //取消按钮
    // cancel() {
    //   this.DialogVisible = false;
    //   this.editForm = null;
    //   this.$emit("cancel");
    // },
    confirm() {
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          this.innerVisible = false;
          this.editForm.farmId = this.farmId;
          if (this.editType == 1 && this.editForm.id) {
            delete this.editForm.id
          }
          this.$emit("confirm", { type: this.type, data: this.editForm ,cropNos: this.cropNos });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.with-full {
  width: 100% !important;
}
</style>